import 'dart:convert';

import 'package:chop/Model/order_entity.dart';
import 'package:chop/Model/user_rider_entity.dart';
import 'package:chop/common/DioUtils.dart';
import 'package:chop/common/JPushUtils.dart';
import 'package:chop/common/SPUtils.dart';
import 'package:chop/view/Driver/riderOrderItem.dart';
import 'package:chop/widgets/TextSizeWidget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/ball_pulse_header.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:geolocator/geolocator.dart';
class NewsOrder extends StatefulWidget {
  final UserRider rider;

  const NewsOrder({Key key, this.rider}) : super(key: key);
  @override
  _NewsOrderState createState() => _NewsOrderState();
}

class _NewsOrderState extends State<NewsOrder> {
  bool isNetWorkBad = false;
  List<orderData> data = [];
  UserRider rider;
  // EasyRefresh控制器
  EasyRefreshController easyRefreshController = EasyRefreshController();
  @override
  void initState() {
    this.rider = widget.rider;
    getRider();

    // TODO: implement initState
    super.initState();
  }
  void getData() async {
    if(rider.open == "0"){
      orderData o = orderData();
      o.status = "0";
      o.riderId = rider.userId;
      await DioUtils.orderList(o).then((val){
        data = [];
        val['data'].forEach((v){
          data.add(orderData.fromJson(v));
        });
        setState(() {
          isNetWorkBad = true;
        });
      });
    }else{
      orderData a = orderData();
      a.status = "3";
      Position nowPosition = await Geolocator()
          .getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
      await DioUtils.unOrders("3",nowPosition.latitude.toString(),nowPosition.longitude.toString()).then((result){
        if(result['code'] == 0){
          result['data'].forEach((v){
            data.add(orderData.fromJson(v));
          });
          setState(() {
            isNetWorkBad = true;
          });
        }

      });
    }

  }
  void getRider() async {
    String UID = await SPUtils.get("UID");
    await DioUtils.riderInfo(UID).then((request) {
      if (request.code == 0) {
        setState(() {
          rider = UserRider.fromJson(json.decode(request.data));
        });
        getData();
      }
    });
  }
  Widget getBody(){
    if(isNetWorkBad){
      // 是否信息完善合格
      if (rider.qualified == "1") {
        // 是否 经过培训
        if (rider.learn == "1") {
          if (rider.open == "1") {
            JPushUtils.beginTimer("${rider.userId}");
            if(data != null){
              return ListView.builder(itemBuilder: (context,index){
                return getOrderItem(context,data: data[index]);
              },itemCount: data.length,);
            }else{
              return Center(child: FixedSizeText("暂无订单"),);
            }
          } else {
            // 判断是否已接单
            if(data.isNotEmpty){
              return ListView.builder(itemBuilder: (context,index){
                return getOrderItem(context,data: data[index]);
              },itemCount: data.length,);
            }else{
              return Center(
                  child: RaisedButton(
                    onPressed: () {
                      DioUtils.riderOpen(rider.userId.toString()).then((result) {
                        print("开始接单：${result.code}");
                        if (result.code == 0) {
                          setState(() {
                            rider.open = "1";
                          });
                        }
                      });
                    },
                    child: FixedSizeText("开始接单"),
                  ));
            }
          }
        } else {
          return Center(
            child: FixedSizeText("请先完成培训"),
          );
        }
      } else {
        return Center(
          child: FixedSizeText("请先完善个人信息"),
        );
      }

    }else{
      return Center(child: CircularProgressIndicator(),);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: EasyRefresh(
        child: getBody(),
        controller: easyRefreshController,
        header: BallPulseHeader(),
//        footer: BallPulseFooter(),
        onRefresh: () async {
          setState(() {
            data = [];
          });
          await getData();
        },
      ),
    );
  }

}
